package edu.hawaii.senin.iclouds.plotting;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.Callable;

import org.jdom.Element;

/**
 * Encapsulates task for plotting routines.
 * 
 * @author Pavel Senin.
 * 
 */
public class EvolutionLogParserTask implements Callable<String> {

  private String logFileName;
  private String outFileName;

  private String populationType;
  private List<String> speciesOfInterest;
  private String kind;
  private String logFormat;

  /**
   * Instantiates the new task from JDOM Element provided.
   * 
   * @param e the element to parse task from.
   * @param speciesOfInterest the list of species of interest.
   * @param kind logger kind, xml or text.
   */
  public EvolutionLogParserTask(Element e, List<String> speciesOfInterest, String kind) {
    this.outFileName = e.getAttributeValue("output_file");
    this.populationType = e.getAttributeValue("population_type");
    this.logFileName = e.getChildText("logfile");
    this.logFormat = e.getChildText("input");
    this.kind = kind;
    this.speciesOfInterest = speciesOfInterest;

  }

  /**
   * Does the actual work.
   * 
   * @return the dummy debug string to be printed as the status on display.
   * @throws Exception if error encountered.
   */
  public String call() throws Exception {

    // parse configs
    EvolutionLogParser logParser = new EvolutionLogParser(this.kind, this.logFormat);
    logParser.parse(logFileName);

    BufferedWriter writer = new BufferedWriter(new FileWriter(new File(this.outFileName)));

    writer.write("accEvent,");
    StringBuilder sb = new StringBuilder(2000);
    for (String spName : this.speciesOfInterest) {
      sb.append(spName + ",");
    }
    writer.write(sb.deleteCharAt(sb.length() - 1) + "\n");

    TreeMap<Long, TreeMap<String, Long>> result = null;
    if ("active".equalsIgnoreCase(this.populationType)) {
      result = logParser.getActivePopulation();
    }
    else if ("buried".equalsIgnoreCase(this.populationType)) {
      result = logParser.getBuriedPopulation();
    }

    for (Long acEvent : result.keySet()) {
      writer.write(acEvent + ",");
      sb = new StringBuilder(2000);
      TreeMap<String, Long> tmpPop = result.get(acEvent);
      for (String spName : this.speciesOfInterest) {
        if (tmpPop.containsKey(spName)) {
          sb.append(tmpPop.get(spName) + ",");
        }
        else {
          sb.append("0,");
        }
      }
      sb.deleteCharAt(sb.length() - 1);
      writer.write(sb + "\n");
    }

    writer.flush();
    writer.close();

    return "Dummy debug: " + this.outFileName + " done!";

  }

}
